const controller = require("../controllers/Controller").controller
const tabber = require("../../utils/tabber")
const app = getApp()
var startPoint
let leftHeight = 0,
  rightHeight = 0; //分别定义左右两边的高度
let query;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value1: {
      pageNumber: 1,
      shopGroupId: "",
      type: 0
    },
    value2: {
      pageNumber: 1,
      shopGroupId: "",
      types: "0,2,3,4,5"
      // type: 2
    },
    clickMe: true,
    buttonRight: 0,
    buttonBottom: 120,
    list2: [],
    leftList: [],
    rightList: [],
    lastPage1: false,
    lastPage2: false,
    scrollIndex: 0,
    userMsg: "",
    totalNum: '',
    shopCircleDetail: "",
    selectIndex: 0,
    name: '',
    imageLoaded: false,
    couponBagNum: 0
  },


  //切换超值推荐和店铺推荐
  changeRecommend(e) {
    console.log(e)
    this.setData({
      selectIndex: e.currentTarget.dataset.index
    })
  },

  //获取商圈详情
  getShopCircleDetail() {
    controller.getShopCircleDetail({
      shopGroupId: this.data.value1.shopGroupId
    }).then(res => {
      this.setData({
        shopCircleDetail: res.data
      })

      this.getActivityPage2()
      this.getCCouponGiftRotationImg()
      this.getShopList()
    })
  },


  //跳转更多商圈
  toMoreShopCircle() {
    wx.navigateTo({
      url: '/pages/TradingArea/TradingArea',
    })
  },

  // 去往个人中心
  goMyCenter() {
    wx.navigateTo({
      url: '/pages/myCenter/myCenter',
    })
  },

  //获取卡券数量
  getTotalNum() {
    controller.getAccountDetail().then(res => {
      this.setData({
        totalNum: res.data.totalNum
      })
    })
  },

  //获取用户个人信息
  getUserMsg() {
    controller.getAccountDetail().then(res => {
      let timeGreet = "";
      let nowTime = new Date().getHours()
      console.log(nowTime)
      if (nowTime == 0) {
        nowTime = 24
      }
      if (nowTime < 8 && nowTime >= 5) {
        timeGreet = "早上"
      } else if (nowTime < 12 && nowTime >= 8) {
        timeGreet = "上午"
      } else if (nowTime < 14 && nowTime >= 12) {
        timeGreet = "中午"
      } else if (nowTime < 18 && nowTime >= 14) {
        timeGreet = "下午"
      } else if (nowTime < 19 && nowTime >= 18) {
        timeGreet = "傍晚"
      } else if (nowTime < 24 && nowTime >= 19) {
        timeGreet = "晚上"
      } else {
        timeGreet = "凌晨"
      }
      this.setData({
        userMsg: res.data,
        timeGreet: timeGreet
      })
    })
  },

  //跳转红包店铺列表
  toClickMe() {
    wx.navigateTo({
      url: '/pages/TradingArea/redBagShopList?id=' + this.data.value1.shopGroupId,
    })
  },

  //以下是按钮拖动事件
  buttonStart: function (e) {
    startPoint = e.touches[0] //获取拖动开始点
  },
  buttonMove: function (e) {
    var endPoint = e.touches[e.touches.length - 1] //获取拖动结束点
    //计算在X轴上拖动的距离和在Y轴上拖动的距离
    var translateX = endPoint.clientX - startPoint.clientX
    var translateY = endPoint.clientY - startPoint.clientY
    startPoint = endPoint //重置开始位置
    var buttonBottom = this.data.buttonBottom - translateY
    var buttonRight = this.data.buttonRight - translateX
    //判断是移动否超出屏幕
    if (buttonRight + 50 >= this.data.windowWidth) {
      buttonRight = this.data.windowWidth - 50;
    }
    if (buttonRight <= 0) {
      buttonRight = 0;
    }
    if (buttonBottom <= 0) {
      buttonBottom = 0
    }
    if (buttonBottom + 50 >= this.data.windowHeight) {
      buttonBottom = this.data.windowHeight - 50;
    }
    this.setData({
      buttonBottom: buttonBottom,
      buttonRight: buttonRight
    })
  },
  buttonEnd: function (e) {},


  //切换tab
  tabChange(e) {
    let index = e.detail.index
    tabber.getRedirectToURI(index)
  },
  toGroupWorkList() {
    wx.navigateTo({
      url: '/pages/TradingArea/groupWorkList?id=' + this.data.value1.shopGroupId,
    })
  },

  toShop(e) {
    let id = e.currentTarget.dataset.shopid
    wx.navigateTo({
      url: '/pages/Index/Index?shopId=' + id,
    })
  },

  //跳转店铺列表
  toShopList() {
    wx.navigateTo({
      url: '/pages/TradingArea/shopCircleShops?id=' + this.data.value1.shopGroupId,
    })
  },


  //获取轮播图
  getCCouponGiftRotationImg() {
    controller.getSwiperImg({
      shopGroupId: this.data.value1.shopGroupId
    }).then(res => {
      this.setData({
        imgList: res.data
      })
    })
  },


  //跳转更多
  toMore(e) {
    let id = e.currentTarget.dataset.id
    if (e.currentTarget.dataset.type || e.currentTarget.dataset.type === 0) {
      let type = e.currentTarget.dataset.type
      wx.navigateTo({
        url: '/pages/TradingArea/ActivityDetail?id=' + id + "&type=" + type,
      })
    } else {
      wx.navigateTo({
        url: '/pages/TradingArea/ActivityDetail?id=' + id,
      })
    }
  },

  //跳转历史活动列表
  toHistryList(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/TradingArea/ActivityDetail?id=' + id + "&history=1",
    })
  },


  //获取商圈的礼券包列表 2.0
  getActivityPage2() {
    let that = this
    let value = this.data.value2
    controller.getMainBagList(value).then(res => {
      res.data.list.forEach(item => {
        if (item.startTime) {
          item.startTime = item.startTime.split(" ")[0]
          item.endTime = item.endTime.split(" ")[0]
        }
      })
      let list = []
      list = res.data.list
      this.setData({
        list2: list,
        lastPage2: res.data.lastPage
      })
      that.waterfallFlow()
    })
  },

  //瀑布流布局
  async waterfallFlow() {
    const {
      list2,
      leftList,
      rightList
    } = this.data;
    query = wx.createSelectorQuery();

    for (let item of list2) {
      // console.log(item)
      leftHeight <= rightHeight ? leftList.push(item) : rightList.push(item); //判断两边高度，来觉得添加到那边
      await this.getBoxHeight(leftList, rightList);
    }

  },
  getBoxHeight(leftList, rightList) {
    return new Promise((resolve, reject) => {
      this.setData({
        leftList,
        rightList
      });
      let query = wx.createSelectorQuery();
      query.select('.left-item').boundingClientRect();
      query.select('.right-item').boundingClientRect();
      // 图片加载完成后再获取列表高度
      let time = setInterval(() => {
        if (this.data.imageLoaded) {
          this.setData({
            imageLoaded: false
          })
          query.exec((res) => {
            leftHeight = res[0].bottom; //获取左边列表的高度
            rightHeight = res[1].bottom; //获取右边列表的高度
            resolve();
          });
          clearInterval(time)
        }
      }, 20)

    })
  },
  // 图片加载完成
  imageLoad() {
    // console.log('imageLoad');
    this.setData({
      imageLoaded: true,
    })
  },

  getScrollLeft(e) {
    let scrollLeft = e.detail.scrollLeft + 26
    let scrollIndex = parseInt(scrollLeft / 128)
    console.log(scrollLeft)
    console.log(scrollIndex)
    this.setData({
      scrollIndex: scrollIndex
    })
  },


  //跳转券包活动详情
  toGiftBagDetail(e) {
    let id = e.currentTarget.dataset.id
    let shopGroupId = e.currentTarget.dataset.shopgroupid
    wx.navigateTo({
      url: '/pages/TradingArea/GiftBagDetail?id=' + id + "&shopGroupId=" + shopGroupId + "&type=0",
    })
  },
  //跳转礼包活动详情
  toGiftBagDetail2(e) {
    let id = e.currentTarget.dataset.id
    let shopGroupId = this.data.value1.shopGroupId
    let ids = e.currentTarget.dataset.ids || 'c'
    let type = e.currentTarget.dataset.type
    wx.navigateTo({
      url: '/pages/TradingArea/GiftBagDetail?id=' + id + "&shopGroupId=" + shopGroupId + "&type=" + type,
    })
  },

  getMore2() {
    let that = this
    if (this.data.lastPage2 == false) {
      let value = this.data.value2
      value.pageNumber = value.pageNumber + 1
      this.setData({
        value2: value
      })
      controller.getMainBagList(value).then(res => {
        res.data.list.forEach(item => {
          if (item.startTime) {
            item.startTime = item.startTime.split(" ")[0]
            item.endTime = item.endTime.split(" ")[0]
          }
        })
        this.setData({
          list2: res.data.list,
          lastPage2: res.data.lastPage
        })
        that.waterfallFlow()
      })
    }
  },
  //用户持有的所有商圈活动的数量统计
  myCouponBagNum() {
    controller.myCouponBagNum().then(res => {

      this.setData({
        couponBagNum: res.data
      })
    })
  },

  //获取店铺列表
  getShopList() {
    controller.getShopCircleShops({
      shopGroupId: this.data.value1.shopGroupId
    }).then(res => {
      let list = res.data
      list.forEach(item => {
        if (item.label) item.label = item.label.split("/")
      })
      this.setData({
        list: list
      })
    })
  },


  //获取商圈列表
  getMyShopCircle() {
    let that = this
    let value = {}
    value.name = ""
    value.pageNumber = 1
    value.lng = app.globalData.lng || ''
    value.lat = app.globalData.lat || ''
    value.pageSize = 10
    controller.getMyShopCircle(value).then(res => {
      // 已有数据不写入，防止消息通知进入时被覆盖
      if (!this.data.name) {
        this.setData({
          lastPage: res.data.lastPage,
          'value1.shopGroupId': res.data.list[0].id,
          'value2.shopGroupId': res.data.list[0].id,
          name: res.data.list[0].name,
          pinNum: parseInt(res.data.list[0].pinNum),
          shamPinNum: parseInt(res.data.list[0].shamPinNum)
        })
      }
      this.getShopCircleDetail()
    })
  },

  getAddress() {
    let that = this
    if (!app.globalData.lat) {
      wx.getLocation({
        success: function (e) {
          console.log(e)
          that.setData({
            lat: e.latitude,
            lng: e.longitude
          })

          app.globalData.lat = e.latitude
          app.globalData.lng = e.longitude
          that.getMyShopCircle()
        },

        fail: function (err) {

        }
      })
    } else {
      that.setData({
        lat: app.globalData.lat,
        lng: app.globalData.lng
      })
      if (that.data.value1.shopGroupId) {
        that.getShopCircleDetail()
      } else {
        that.getMyShopCircle()
      }
    }
  },


  //重新设置地址授权
  openSet() {
    let that = this

    wx.getLocation({
      success: function (e) {
        console.log(e)
        that.setData({
          lat: e.latitude,
          lng: e.longitude
        })
        app.globalData.lat = e.latitude
        app.globalData.lng = e.longitude
        that.getMyShopCircle()
      },
      fail: function (err) {
        console.log(err);

        if (err.errCode == 2) {
          wx.showModal({
            content: "请打开手机定位系统",
            confirmText: "知道了",
            showCancel: false,
          })
        } else if (err.errno == 103) {
          wx.showModal({
            content: "打开设置页并允许该小程序获取位置信息",
            confirmText: "打开",
            cancelText: "拒绝",
            success: (res) => {
              if (res.confirm) {
                wx.openSetting({
                  success: (res) => {
                    if (res.authSetting['scope.userLocation']) {
                      that.getAddress()
                    }
                  }
                })
              }
            }
          })

        }
      }
    })
  },

  //阻止冒泡
  stop() {

  },



  //关闭红包
  closeRed() {
    let that = this
    this.setData({
      closeAnimate: false
    })
    setTimeout(function () {
      that.setData({
        redShow: false,
        closeAnimate: false,
        isReceived: false
      })
      that.setData({
        redTimer: setInterval(function () {
          let page = getCurrentPages()
          if (page[page.length - 1].route != 'pages/TradingArea/index') {
            return
          }
          that.selectTransactionRed()
        }, 6000)
      })
    }, 280)
  },

  //获取用户可领取红包
  selectTransactionRed() {
    let that = this
    controller.selectTransactionRed().then(res => {
      if (res.data.redList.length > 0) {
        this.setData({
          redList: res.data.redList
        })
        // if (this.data.redList[0].type == 10) {
        //   this.setData({
        //     redText: "一卡通奖励"
        //   })
        // } else if (this.data.redList[0].type == 12) {
        //   this.setData({
        //     redText: "爆品奖励"
        //   })
        // }else if (this.data.redList[0].type == 22) {
        //   this.setData({
        //     redText: "限时抵用券奖励"
        //   })
        // }else if (this.data.redList[0].type == 23) {
        //   this.setData({
        //     redText: "超值礼包奖励"
        //   })
        // } else {
        //   this.setData({
        //     redText: "拼团失败奖励"
        //   })
        // }
        that.setData({
          redShow: true,
          closeAnimate: true,
          redPrice: this.data.redList[0].value
        })
        clearInterval(that.data.redTimer)
      }
    })
  },

  //领取红包
  giveTransactionRed() {
    if (this.data.redList.length > 0) {
      let value = {}
      value.transactionId = this.data.redList[0].id
      controller.giveTransactionRed(value).then(res => {
        wx.showToast({
          icon: 'none',
          title: '领取成功',
        })
        this.setData({
          isReceived: true
        })
      })
    }
  },

  toMyAccount() {
    this.setData({
      redShow: false,
      closeAnimate: false,
      isReceived: false
    })
    this.setData({
      redTimer: setInterval(function () {
        let page = getCurrentPages()
        if (page[page.length - 1].route != 'pages/TradingArea/index') {
          return
        }
        this.selectTransactionRed()
      }, 6000)
    })
    wx.navigateTo({
      url: '/pages/myCenter/myAccount',
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options && options.id) {
      this.setData({
        'value1.shopGroupId': options.id,
        'value2.shopGroupId': options.id,
        pinNum: parseInt(options.pinNum),
        shamPinNum: parseInt(options.shamPinNum),
        // 对转发进入页面的中文进行转码
        name: decodeURIComponent(options.name),
      })
    }


    this.setData({
      tabbar: app.globalData.tabbar3
    })

    let page = getCurrentPages()
    console.log(page[page.length - 1].route)

    let that = this
    //请求红包并判断是否可以开启定时器
    if (wx.getStorageSync('usertoken')) {
      //加载首页数据
      this.getAddress()
      this.getUserMsg()
      this.getTotalNum()
      this.myCouponBagNum()
      controller.selectTransactionRed().then(res => {
        //定时检测并弹出红包
        if (!this.data.redTimer) {
          that.setData({
            redTimer: setInterval(function () {
              let page = getCurrentPages()
              if (page[page.length - 1].route != 'pages/TradingArea/index') {
                return
              }

              that.selectTransactionRed()
            }, 6000)
          })
        }
        if (res.data.redList.length > 0) {
          this.setData({
            redList: res.data.redList
          })
          // if(this.data.redList[0].type==10){
          //   this.setData({
          //     redText:"一卡通奖励"
          //   })
          // }else if(this.data.redList[0].type==12){
          //   this.setData({
          //     redText:"爆品奖励"
          //   })
          // }else if(this.data.redList[0].type==22){
          //   this.setData({
          //     redText:"限时抵用券奖励"
          //   })
          // }else if(this.data.redList[0].type==12){
          //   this.setData({
          //     redText:"超值礼包奖励"
          //   })
          // }else{
          //   this.setData({
          //     redText:"拼团失败奖励"
          //   })
          // }
          that.setData({
            redShow: true,
            closeAnimate: true,
            redPrice: this.data.redList[0].value
          })
          clearInterval(that.data.redTimer)
        }
      })
    } else {
      //无usertoken，等待login登录回调
      app.usertokenReadyCallback = res => {
        if (res.data.sessionId) {
          this.getAddress()
          this.getUserMsg()
          this.getTotalNum()
          this.myCouponBagNum()
          controller.selectTransactionRed().then(res => {
            //定时检测并弹出红包
            if (!this.data.redTimer) {
              that.setData({
                redTimer: setInterval(function () {
                  let page = getCurrentPages()
                  if (page[page.length - 1].route != 'pages/TradingArea/index') {
                    return
                  }
                  that.selectTransactionRed()
                }, 6000)
              })
            }
            if (res.data.redList.length > 0) {
              this.setData({
                redList: res.data.redList
              })
              // if(this.data.redList[0].type==10){
              //   this.setData({
              //     redText:"一卡通奖励"
              //   })
              // }else if(this.data.redList[0].type==12){
              //   this.setData({
              //     redText:"爆品奖励"
              //   })
              // }else if(this.data.redList[0].type==22){
              //   this.setData({
              //     redText:"限时抵用券奖励"
              //   })
              // }else if(this.data.redList[0].type==23){
              //   this.setData({
              //     redText:"超值礼包奖励"
              //   })
              // }else{
              //   this.setData({
              //     redText:"拼团失败奖励"
              //   })
              // }
              that.setData({
                redShow: true,
                closeAnimate: true,
                redPrice: this.data.redList[0].value
              })
              clearInterval(that.data.redTimer)
            }

          })
        }
      }
    }
    // 分享朋友圈
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareTimeline'],
    })
  },

  onShareAppMessage() {

  },
  onShareTimeline() {

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let that = this
    console.log("清除计时器")
    leftHeight = 0, rightHeight = 0;
    clearInterval(that.data.redTimer)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.selectIndex == 0) {
      this.getMore2()
    }
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
})